<?php
/**
 * Author: 式神(vashi)
 * email: 289650682@qq.com
 * Date: 2019/1/7 16:56
 * FileName: Admin.php
 */

namespace app\common\model;


use luck\Crypt;
use think\Model;
use app\common\validate\Admin as AdminValidate;

class Admin extends Model
{
    protected $connection = 'admin';
    protected $readonly = ['username'];   //不能修改的字段
    protected $tip_name = '后台用户';
    protected $validate;
    protected $crypt;

    public function initialize()
    {
        parent::initialize();
        $this->crypt=config('app.crypt.md5').config('app.crypt.key');
        $this->validate=new AdminValidate;
    }

    public function roleGroup()
    {
        return $this->belongsToMany('Role','authGroupAccess','group_id','uid');
    }

    /**
     * 登录处理
     */
    public function login($data){
        //1.执行验证
        $res=[
            'code'=>1,
            'msg'=>'验证失败',
        ];
        if(!$this->validate->scene('login')->check($data)){
            $res['msg']=$this->validate->getError();
            return $res;
        }
        //检测用户名和密码是否匹配
        $userInfo=$this->where('username',$data['username'])
            ->where('password',Crypt::encrypt($data['password'],$this->crypt))
            ->find();
        if(!$userInfo){
            //数据库没有数据
            $res['msg']='用户名或者密码不正确!';
            return $res;
        }
        if($userInfo['status']!=1){
            $res['msg']='用户被禁用!';
            return $res;
        }

        //更新登陆时间
        $up= $this->save([
            'num'=>['inc','1'],
            'last_login_time'=>time(),
            'last_login_ip'=>sprintf("%u",ip2long(request()->ip())),
        ],[$this->pk=>$userInfo['id']]);
        if(!$up){
            $res['msg']='登陆失败,请重试！';
            return $res;
        }
        $res['data']=[
            config('app.ADMIN_AUTH_KEY')=>$userInfo['id'],
            config('app.ADMIN_AUTH_NAME')=>$userInfo['username']
        ];
        $res['code']=0;
        $res['msg']='登录成功!';
        return $res;
    }

    //添加管理员
    public function add($input){
        //1.执行验证
        $res=[
            'code'=>3,
            'msg'=>'验证失败',
        ];
        //空密码设置
        if(!isset($input['password']) || !$input['password']){
            $input['password']='123456';
        }

        if(!$this->validate->scene('create')->check($input)){
            $res['msg']=$this->validate->getError();
            return $res;
        }
        //验证用户名重复
        $userInfo=$this->where('username',$input['username'])->find();
        if($userInfo){
            $res['msg']='用户名已经存在！';
            return $res;
        }
        //添加数据
        $input['password']=Crypt::encrypt($input['password'],$this->crypt);
        $input['update_time']= $input['create_time']=request()->time();

        if(!isset($input['status']) || !$input['status']){
            $input['status']=0;
        }
        $data=$this->save($input);
        if($data){
            $res['code']=0;
            $res['msg']=$this->tip_name.'添加成功！';
        }else{
            $res['msg']=$this->tip_name.'添加失败,请重试！';
        }
        return $res;
    }

    //编辑管理员
    public function edit($input){
        //1.执行验证
        $res=[
            'code'=>3,
            'msg'=>'验证失败',
        ];
        if(!$this->validate->scene('edit')->check($input)){
            $res['msg']=$this->validate->getError();
            return $res;
        }
        //验证用户名重复
        $userInfo=$this->where('username',$input['username'])->where('id','NEQ',$input['id'])->find();
        if($userInfo){
            $res['msg']='用户名已经存在！';
            return $res;
        }
        //添加数据
        if(!isset($input['password']) || !$input['password']){
            unset($input['password']);
        }else{
            $input['password']=Crypt::encrypt($input['password'],$this->crypt);
        }
        $input['update_time']=request()->time();

        if(!isset($input['status']) || !$input['status']){
            $input['status']=0;
        }
        $data=$this->save($input,[$this->pk=>$input['id']]);
        if($data){
            $res['code']=0;
            $res['msg']=$this->tip_name.'修改成功！';
        }else{
            $res['msg']=$this->tip_name.'修改失败,请重试！';
        }
        return $res;
    }

    public function del($input){
        $ids=array_unique($input);
        $fids=array_flip($ids);
        unset($fids[session(config('auth.ADMIN_AUTH_KEY'))]);
        $ids=array_flip($fids);
        $res=[
            'code'=>3,
            'msg'=>'删除失败',
        ];
        if(count($ids)>0) {
            if ($this->destroy($ids,true)) {
                $res['code'] = 0;
                $res['msg'] = '删除'.$this->tip_name.'成功！';
            } else {
                $res['msg'] = '删除'.$this->tip_name.'失败,请重试！';
            }
        }else{
            $res['msg']='删除'.$this->tip_name.'失败,存在不能删除的数据,请重试！';
        }
        return $res;
    }
}